09. Exercise: Dates and Calendar

Exercise: Dates and Calendar

Create a DatesAndCalendar class

Task Description:

In this exercise, we'll create a class to get some practice using the Date and Calendar classes to get and store dates in Java.

Task List:

Task Feedback:

Nice work!

Add a displaySetDate method

Task Description:

Next you will be adding another method to the 'DatesAndCalendar' class created above:

Task List:

Task Feedback:

Nice work!

Solution

ND079 C1 L4 A09 Dates And Calendar Solutions

The key points to take from this are:

  • You can use the Calendar class to get the current date, and to set the date.
  • Typically, dates are stored in the Date class.
  • The calendar.setTime(date); and calendar.getTime() can be used to go back and forth between the Date and Calendar classes.

Note: You can use SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); to change the format of dates

public class DatesAndCalendar {

    public static void main(String[] args) {
        DatesAndCalendar.displayCurrentDate();
        DatesAndCalendar.displaySetDate();
    }

    private static void displayCurrentDate() {
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar);
        Date date = new java.util.Date();
        calendar.setTime(date);
        System.out.println(calendar.getTime());
    }

    private static void displaySetDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2031, 02, 02);
        Date date = calendar.getTime();

        System.out.println(date);
    }

}